<?php
namespace app\plat\controller;

use think\Db;

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/8/22
 * Time: 11:07
 */
class Login extends \think\Controller
{
    public function __construct()
    {
        parent::__construct();
        if(session("?plat")){
            $this->redirect(url('index/index'));
        }
    }

    public function index()
    {
        return $this->fetch();
    }

    public function ajax_login()
    {
        $username = input('username');
        $password = md5(input('password'));

        $a = Db::name('admin')->where('username',$username)->where('password',$password)->field('password',true)->find();
        //此处需要获取权限
//
        if(!$a){
            $this->error('账号或密码不正确');
        }
        if($a){
            if($a['status']==0){
                $this->error('账号被锁定');
            }
            $data['modtime'] = $data['log_time'] = time();
            $data['log_ip'] = request()->ip();
            Db::name('admin')->where('id',$a['id'])->update($data);
            session('plat',$a);
            $this->nav($a);
            $this->success('登录成功',url('index/index'));
        }
    }

    public function nav($admin)
    {
        $nav = [];
        $nodes =[];
        if($admin['is_super']){
            $nodes = Db::name('rbac_node')
                ->where('display',1)
                ->where('level','in',[1,2])
                ->order('sort desc,id desc')
                ->select();
        }else if($admin['role_id']){
            $nodes = Db::name('rbac_access')
                ->alias('a')
                ->join('rbac_node b','b.id=a.node_id')
                ->where('a.role_id',$admin['role_id'])
                ->where('b.display',1)
                ->where('b.level','in',[1,2])
                ->order('b.sort desc,b.id desc')
                ->field('b.*')
                ->select();

        }
        if($nodes){
            foreach ($nodes as $value)
            {
                if($value['level']==1){
                    $a = $value;
                    $a['items'] = [];
                    foreach ($nodes as $k=>$v)
                    {
                        if($v['pid'] == $value['id']){
                            $a['items'][] = $v;
                            unset($nodes[$k]);
                        }
                    }
                    $nav[] = $a;
                }
            }
        }
        session('nav',$nav);
    }
}